<template>
  <canvas ref="canvas" class="matrix-bg"></canvas>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'

const canvas = ref<any>(null)
let animationId:any = null

onMounted(() => {
  const ctx = canvas.value.getContext('2d')
  let width = canvas.value.width = window.innerWidth
  let height = canvas.value.height = window.innerHeight

  // 字符集
  const chars = '01'
  // 字符大小
  const fontSize = 14
  const columns = width / fontSize

  // 每列字符的当前y坐标
  const drops = new Array(Math.floor(columns)).fill(1)

  function draw() {
    // 设置半透明黑色背景，形成渐隐效果
    ctx.fillStyle = 'rgba(0, 0, 0, 0.05)'
    ctx.fillRect(0, 0, width, height)

    // 设置文字颜色和字体
    ctx.fillStyle = '#0F0' // 黑客帝国风格的绿色
    ctx.font = `${fontSize}px monospace`

    // 绘制字符
    for (let i = 0; i < drops.length; i++) {
      const text = chars[Math.floor(Math.random() * chars.length)]
      ctx.fillText(text, i * fontSize, drops[i] * fontSize)

      // 当字符到达底部或随机位置时，重置到顶部
      if (drops[i] * fontSize > height && Math.random() > 0.975) {
        drops[i] = 0
      }
      drops[i]++
    }

    animationId = requestAnimationFrame(draw)
  }

  // 处理窗口大小变化
  const handleResize = () => {
    width = canvas.value.width = window.innerWidth
    height = canvas.value.height = window.innerHeight
  }
  window.addEventListener('resize', handleResize)

  draw()

  // 清理事件监听
  onUnmounted(() => {
    window.removeEventListener('resize', handleResize)
    if (animationId) {
      cancelAnimationFrame(animationId)
    }
  })
})
</script>

<style scoped>
.matrix-bg {
  position: fixed;
  top: 0;
  left: 0;
  z-index: -1;
  background: black;
}
</style> 